/**
 Mock.Random 提供的完整方法（占位符）如下：

 Type    Method
 Basic    boolean, natural, integer, float, character, string, range, date, time, datetime, now
 Image    image, dataImage
 Color    color
 Text    paragraph, sentence, word, title, cparagraph, csentence, cword, ctitle
 Name    first, last, name, cfirst, clast, cname
 Web    url, domain, email, ip, tld
 Address    area, region
 Helper    capitalize, upper, lower, pick, shuffle
 Miscellaneous    guid, id
 */
(function () {
    var Random = Mock.Random;

    function objLength(obj) {
        var length = 0;
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                length++;
            }
        }
        return length;
    }

    //接口模拟二次封装
    function _Mock(url, type, callback) {
        // Mock.mock(template)
        if (arguments.length === 1) {
            callback = url;
        }
        // Mock.mock(rurl, template)
        if (arguments.length === 2) {
            callback = type
        }
        Mock.mock(api_url + url, type, function (options) {
            var params = $.paramToObj(options.body);
            var result = callback(params);
            console.log(options.url, options.type, params, result);
            return result;
        });
    }

    //扩展返回状态
    function errorCode(codes) {
        return $.extend(codes, {"10001": "登录状态失效"});
    }

    //结果类
    function Result(returnState, returnMsg, returnData) {
        return {
            returnState: returnState || 0,
            returnMsg: returnMsg || "success",
            returnData: returnData || null
        };
    }

    //(value = "移动端用户信息")
    function AppUser(obj) {
        return {
            //(notes = "主键")
            id: obj.id || Random.natural(1, 10000),
            //(notes = "姓名")
            fullName: obj.fullName || Random.cname(),
            //(notes = "手机号")
            mobileNumber: obj.mobileNumber || "1" + Random.string('0123456789', 10),
            //(notes = "头像")
            headImg: obj.headImg || Random.dataImage(),
            //(notes = "密码")
            password: obj.password || Random.string('abcdefghijklmnopqrstuvwxyz0123456789', 32),
            //(notes = "用户角色:obj.//(notes = "用户角色||1-普通用户，接单员-2")
            userRole: obj.userRole || Random.natural(1, 2),
            //(notes = "注册日期")
            registerDate: obj.registerDate || Random.date(),
            //(notes = "登录次数")
            loginCount: obj.loginCount || Random.natural(1, 10000),
            //(notes = "认证token")
            token: obj.token || Random.guid(),
            //(notes = "登录时间")
            loginTime: obj.loginTime || Random.datetime(),
            //(notes = "token更新时间")
            tokenRefreshTime: obj.tokenRefreshTime || Random.datetime(),
            //(notes = "删除状态")
            delStatus: obj.delStatus || Random.natural(0, 1)
        };
    }

    //(value = "咨询订单")
    function ConsultOrder(obj) {
        return {
            //(notes = "主键")
            id: obj.id || Random.natural(1, 10000),
            //(notes = "政策id")
            policyId: obj.policyId || Random.natural(1, 10000),
            //(notes = "用户id")
            appUserId: obj.appUserId || Random.natural(1, 10000),
            //(notes = "匹配结果id")
            matchResultId: obj.matchResultId || Random.natural(1, 10000),
            //(notes = "接单人id")
            serverId: obj.serverId || Random.natural(1, 10000),
            //(notes = "订单状态：0-待咨询，1-咨询中，2-已完成，3-已取消")
            status: obj.status || Random.natural(0, 3),
            //(notes = "删除状态")
            delStatus: obj.delStatus || Random.natural(0, 1),
            //(notes = "数据更新时间")
            updateTime: obj.updateTime || Random.datetime(),
            //(notes = "咨询时间")
            createTime: obj.createTime || Random.datetime(),
            //(notes = "政策标题")
            policyTitle: obj.policyTitle || Random.ctitle(3, 7),
            //(notes = "下单人")
            appUserName: obj.appUserName || Random.cname(),
            //(notes = "接单人")
            serverUserName: obj.serverUserName || Random.cname()
        };
    }

    //(value = "时势管理")
    function Events(obj) {
        if (Math.random() > 0.9) {
            return {
                //(notes = "主键")
                id: obj.id || Random.natural(1, 10000),
                //(notes = "标题")
                title: obj.title || Random.ctitle(3, 7),
                //(notes = "查阅人数")
                viewCount: obj.viewCount || Random.natural(1, 10000),
                //(notes = "封面图")
                coverImg: [Random.dataImage(), Random.dataImage(), Random.dataImage()],
                //(notes = "内容")
                content: obj.content || Random.cparagraph(3, 7),
                //(notes = "删除状态")
                delStatus: obj.delStatus || Random.natural(0, 1),
                //(notes = "数据更新时间")
                updateTime: obj.updateTime || Random.datetime(),
                //(notes = "数据添加时间")
                createTime: obj.createTime || Random.datetime()
            };
        }
        return {
            //(notes = "主键")
            id: obj.id || Random.natural(1, 10000),
            //(notes = "标题")
            title: obj.title || Random.ctitle(3, 7),
            //(notes = "查阅人数")
            viewCount: obj.viewCount || Random.natural(1, 10000),
            //(notes = "封面图")
            coverImg: obj.coverImg || [Random.dataImage()],
            //(notes = "内容")
            content: obj.content || Random.cparagraph(3, 7),
            //(notes = "删除状态")
            delStatus: obj.delStatus || Random.natural(0, 1),
            //(notes = "数据更新时间")
            updateTime: obj.updateTime || Random.datetime(),
            //(notes = "数据添加时间")
            createTime: obj.createTime || Random.datetime()
        };
    }

    //(value = "攻略表")
    function Guides(obj) {
        return {
            //(notes = "主键")
            id: obj.id || Random.natural(1, 10000),
            //(notes = "关联政策id")
            policyId: obj.policyId || Random.natural(1, 10000),
            //(notes = "标题")
            title: obj.title || Random.ctitle(3, 7),
            //(notes = "查阅人数")
            viewCount: obj.viewCount || Random.natural(1, 10000),
            //(notes = "收藏人数")
            collection: obj.collection || Random.natural(1, 10000),
            //(notes = "封面图")
            coverImg: obj.coverImg || Random.dataImage(),
            //(notes = "视频")
            video: obj.video || "../../../img/video.MP4",
            //(notes = "视频长度")
            videoLength: obj.videoLength || Random.time(),
            //(notes = "作者")
            author: obj.author || Random.cname(),
            //(notes = "内容")
            content: obj.content || Random.cparagraph(3, 7),
            //(notes = "删除状态")
            delStatus: obj.delStatus || Random.natural(0, 1),
            //(notes = "数据更新时间")
            updateTime: obj.updateTime || Random.datetime(),
            //(notes = "数据添加时间")
            createTime: obj.createTime || Random.datetime()
        };
    }

    //(value = "首页资讯")
    function HomeNews(obj) {
        return {
            //(notes = "主键")
            id: obj.id || Random.natural(1, 10000),
            //(notes = "标题")
            title: obj.title || Random.ctitle(3, 7),
            //(notes = "内容")
            content: obj.content || Random.cparagraph(3, 7),
            //(notes = "封面图")
            coverImg: obj.coverImg || Random.dataImage(),
            //(notes = "创建时间")
            createTime: obj.createTime || Random.datetime(),
            //(notes = "修改时间")
            updateTime: obj.updateTime || Random.datetime(),
            //(notes = "删除状态，0可用，1已删除")
            delStatus: obj.delStatus || Random.natural(0, 1)
        };
    }

    //(value = "政策匹配项")
    function MatchConfig(obj) {
        return {
            //(notes = "主键")
            id: obj.id || Random.natural(1, 10000),
            //(notes = "匹配项目名称")
            name: obj.name || Random.ctitle(2, 4),
//(notes = "1:obj.//(notes = "1||数值类型，2:boolean类型，3:下拉选，4:文本类型")
            type: obj.type || Random.natural(1, 4),
            //(notes = "是否必填，0选填，1必填")
            isRequired: obj.isRequired || Random.natural(0, 1),
            //(notes = "匹配项key")
            entryKey: obj.entryKey || Random.string("lower", 1, 32),
            //(notes = "显示排序")
            sort: obj.sort || Random.natural(1, 10000),
//(notes = "0:obj.//(notes = "0||删除;1:正常")
            delStatus: obj.delStatus || Random.natural(0, 1),
            //(notes = "数据更新时间")
            updateTime: obj.updateTime || Random.datetime(),
            //(notes = "数据添加时间")
            createTime: obj.createTime || Random.datetime()
        };
    }

    //(value = "政策信息")
    function PolicyInfo(obj) {
        return {
            //(notes = "主键")
            id: obj.id || Random.natural(1, 10000),
            //(notes = "标题")
            title: obj.title || Random.ctitle(3, 7),
            //(notes = "查阅人数")
            viewCount: obj.viewCount || Random.natural(1, 10000),
            //(notes = "封面图")
            coverImg: obj.coverImg || Random.dataImage(),
            //(notes = "内容")
            content: obj.content || Random.cparagraph(3, 7),
            //(notes = "附件")
            attachment: obj.attachment || "",
            //(notes = "删除状态")
            delStatus: obj.delStatus || Random.natural(0, 1),
            //(notes = "数据更新时间")
            updateTime: obj.updateTime || Random.datetime(),
            //(notes = "数据添加时间")
            createTime: obj.createTime || Random.datetime(),
            attachmentList: obj.attachmentList || []
        };
    }

    var mockData = {}, EventList = [], GuideList = [], NewsList = [], PolicyList = [];
    if (localStorage.getItem("mockData")) {
        mockData = JSON.parse(localStorage.getItem("mockData"));
        EventList = mockData.EventList;
        GuideList = mockData.GuideList;
        NewsList = mockData.NewsList;
        PolicyList = mockData.PolicyList;
    } else {
        for (var i = 0; i < 49; i++) {
            EventList.push(new Events({id: i + 1}));
        }
        for (i = 0; i < 49; i++) {
            GuideList.push(new Guides({id: i + 1}));
        }
        for (i = 0; i < 49; i++) {
            NewsList.push(new HomeNews({id: i + 1}));
        }
        for (i = 0; i < 49; i++) {
            PolicyList.push(new PolicyInfo({id: i + 1}));
        }
        mockData.EventList = EventList;
        mockData.GuideList = GuideList;
        mockData.NewsList = NewsList;
        mockData.PolicyList = PolicyList;
        localStorage.setItem("mockData", JSON.stringify(mockData));
    }


    //登录接口
    _Mock("/login", function (params) {
        var _errorCode = errorCode({"0": "登陆成功", "1": "用户名不存在", "2": "密码错误", "3": "账号被冻结"});
        var result = new Result();
        var r = Math.floor(Math.random() * objLength(_errorCode));
        switch (r) {
            case 0: {
                result.returnData = new AppUser();
                break;
            }
        }
        result.returnState = r;
        result.returnMsg = _errorCode[r + ""];
        return result;
    });

    //注册接口
    _Mock("/register", function (params) {
        console.log(params);
        var result = new Result();
        if (Math.random() > 0.5) {
            result.data = new Car();
        } else {
            result.returnState = 1;
            result.returnMsg = "error";
        }
        return result;
    });

    //
    _Mock("/events/list", "post", function (params) {
        var result = new Result();
        if (isNaN(parseInt(params.current)) || isNaN(parseInt(params.count))) {
            result.returnState = "10000";
            result.returnMsg = "参数错误！";
            return result;
        }
        if (parseInt(params.current) >= EventList.length) {
            result.returnState = "1";
            result.returnMsg = "没有更多！";
            result.returnData = [];
            return result;
        }
        result.returnState = "0";
        result.returnMsg = "查询成功！";
        result.returnData = [];
        for (var i = parseInt(params.current); i < parseInt(params.current) + parseInt(params.count); i++) {
            if (EventList[i])
                result.returnData.push(EventList[i]);
        }
        return result;
    });
    //
    _Mock("/events/detail", "post", function (params) {
        var result = new Result();
        if (isNaN(params.id)) {
            result.returnState = "10000";
            result.returnMsg = "参数错误！";
            return result;
        }
        if (parseInt(params.current) >= EventList.length) {
            result.returnState = "1";
            result.returnMsg = "您访问的内容已不存在！";
            result.returnData = null;
            return result;
        }
        result.returnState = "0";
        result.returnMsg = "查询成功！";
        result.returnData = EventList[params.id - 1];
        return result;
    });
    //
    _Mock("/policy/list", "post", function (params) {
        var result = new Result();
        if (isNaN(parseInt(params.current)) || isNaN(parseInt(params.count))) {
            result.returnState = "10000";
            result.returnMsg = "参数错误！";
            return result;
        }
        if (parseInt(params.current) >= PolicyList.length) {
            result.returnState = "1";
            result.returnMsg = "没有更多！";
            result.returnData = [];
            return result;
        }
        result.returnState = "0";
        result.returnMsg = "查询成功！";
        result.returnData = [];
        for (var i = parseInt(params.current); i < parseInt(params.current) + parseInt(params.count); i++) {
            if (PolicyList[i])
                result.returnData.push(PolicyList[i]);
        }
        return result;
    });
    //
    _Mock("/policy/detail", "post", function (params) {
        var result = new Result();
        if (isNaN(params.id)) {
            result.returnState = "10000";
            result.returnMsg = "参数错误！";
            return result;
        }
        if (parseInt(params.current) >= PolicyList.length) {
            result.returnState = "1";
            result.returnMsg = "您访问的内容已不存在！";
            result.returnData = null;
            return result;
        }
        result.returnState = "0";
        result.returnMsg = "查询成功！";
        result.returnData = PolicyList[params.id - 1];
        return result;
    });
    //
    _Mock("/video/list", "post", function (params) {
        var result = new Result();
        if (isNaN(parseInt(params.current)) || isNaN(parseInt(params.count))) {
            result.returnState = "10000";
            result.returnMsg = "参数错误！";
            return result;
        }
        if (parseInt(params.current) >= GuideList.length) {
            result.returnState = "1";
            result.returnMsg = "没有更多！";
            result.returnData = [];
            return result;
        }
        result.returnState = "0";
        result.returnMsg = "查询成功！";
        result.returnData = [];
        for (var i = parseInt(params.current); i < parseInt(params.current) + parseInt(params.count); i++) {
            if (GuideList[i])
                result.returnData.push(GuideList[i]);
        }
        return result;
    });
    //
    _Mock("/video/detail", "post", function (params) {
        var result = new Result();
        if (isNaN(params.id)) {
            result.returnState = "10000";
            result.returnMsg = "参数错误！";
            return result;
        }
        if (parseInt(params.current) >= GuideList.length) {
            result.returnState = "1";
            result.returnMsg = "您访问的内容已不存在！";
            result.returnData = null;
            return result;
        }
        result.returnState = "0";
        result.returnMsg = "查询成功！";
        result.returnData = GuideList[params.id - 1];
        return result;
    });
})();